// @flow
import React, { Component } from 'react'
import { Modal, message } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
type Props = {
  visible: boolean,
  closeModal: Function,
  deviceId?: string,
  kmxData: Array<Object>
}
type States = {
  loading: boolean
}

class SyncKMX extends Component {
  props: Props
  state: States
  syncKMX: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false
    }
    this.syncKMX = this.syncKMX.bind(this)
  }

  syncKMX () {
    const { closeModal, kmxData } = this.props
    this.setState({
      loading: true
    })
    kmxData.map((d, i) => {
      if (d.parentId === 0) {
        universalFetch(`${__SERVICE_API__}device/kmx/meta2kmx?id=${d.id}`)
          .then(res => res.json())
          .then((json) => {
            if (json.code !== 200000) {
              throw new Error(JSON.stringify({ code: json.code, message: json.message }))
            }
            this.setState({
              loading: false
            })
            closeModal()
            message.success('同步选中设置成功')
          })
          .catch((error) => {
            handleFetchError(error)
            console.error(error)
            this.setState({
              loading: false
            })
            message.error('同步选中设置失败: ' + error.message)
          })
      } else {
        this.setState({
          loading: false
        })
        message.info('此数据不能同步')
      }
    })
  }
  render () {
    const { visible, closeModal } = this.props
    const { loading } = this.state
    return (
      <Modal title='同步选中设置'
        visible={visible}
        onCancel={closeModal}
        confirmLoading={loading}
        maskClosable={false}
        onOk={this.syncKMX}
        >
        <div>
          <p>确定要同步选中设置吗？</p>
        </div>
      </Modal>
    )
  }
}

export default SyncKMX
